package com.gk.panda.apis.controller;

import com.gk.panda.apis.dto.FileDownloadDto;
import com.gk.panda.apis.service.FdfsService;
import com.gk.panda.commons.exception.ServerException;
import com.gk.panda.commons.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName: FileController
 * @Description: 文件接口
 * @author: Sir.yang
 * @date: 2022/11/6 10:23
 * @version: 1.0
 **/
@RestController
@Api(tags = "文件接口")
@RequestMapping("/file")
public class FileController {

    @Autowired
    private FdfsService fdfsService;

    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public Result<String> uploadFile(MultipartFile file) {
        if (null != file) {
            //获取文件上传的名称
            String originalFilename = file.getOriginalFilename();
            if (StringUtils.isBlank(originalFilename)) {
                throw new ServerException("上传文件有误，请确认！");
            }

            String[] fileNameAttr = originalFilename.split("\\.");
            //获取文件的后缀
            String suffix = fileNameAttr[fileNameAttr.length - 1];
            //格式较多
//            if (!Arrays.asList(Constants.FILE_SUFFIX).contains(suffix)) {
//                throw new ServerException("上传的文件格式不正确！");
//            }
            return Result.ok(fdfsService.uploadFile(file, suffix));

        }
        return Result.error("文件不能为空！");
    }


    @ApiOperation("文件删除")
    @GetMapping("/del")
    public Result<String> delFile(@RequestParam(value = "filePath") String filePath) {
        fdfsService.deleteFile(filePath);
        return Result.write(200,"删除成功");
    }


    @ApiOperation("文件下载")
    @PostMapping("/download")
    public void downloadFile(@RequestBody FileDownloadDto dto, HttpServletResponse response) {
        if (StringUtils.isEmpty(dto.getFilePath())) {
            throw new ServerException("文件地址不能为空");
        }
        fdfsService.fileDownLoad(dto.getFilePath(),response);
    }
}
